﻿using AutoTask.Model;
using AutoTask.Model.DB;
using RpcHelper;
using SqlSugarHelper;

namespace AutoTask.DAL.Repository
{
    internal class AutoTaskDAL : IAutoTaskDAL
    {
        private IRepository<AutoTaskModel> _BasicDAL;
        public AutoTaskDAL(IRepository<AutoTaskModel> dal)
        {
            _BasicDAL = dal;
        }
        public BasicTask[] GetTaskList(long regionId)
        {
            return this._BasicDAL.Gets(c => c.RegionId == regionId && c.IsEnable, c => new BasicTask
            {
                Id = c.Id,
                TaskPriority = c.TaskPriority,
                VerNum = c.VerNum
            });
        }
        public TaskState GetTaskState(Guid id)
        {
            return this._BasicDAL.Get(a => a.Id == id, c => new TaskState
            {
                ExecVerNum = c.ExecVerNum,
                NextExecTime = c.NextExecTime
            });
        }
        public RemoteTask GetTask(Guid id)
        {
            return this._BasicDAL.Get(a => a.Id == id, c => new RemoteTask
            {
                BeginItem = c.BeginItem,
                FailEmall = c.FailEmall,
                RegionId = c.RegionId,
                TaskName = c.TaskName,
                TaskPriority = c.TaskPriority,
                TaskShow = c.TaskShow
            });
        }

        public void StopTask(Guid id, long errorId)
        {
            if (!this._BasicDAL.Update(a => new AutoTaskModel
            {
                NextExecTime = null,
                IsEnable = false
            }, c => c.Id == id))
            {
                throw new ErrorException("task.stop.fail");
            }
        }

        public void EndExec(Guid id)
        {
            if (!this._BasicDAL.Update(a => new AutoTaskModel
            {
                LastExecEndTime = DateTime.Now,
                IsExec = false
            }, c => c.Id == id))
            {
                throw new ErrorException("task.end.fail");
            }
        }
        public bool BeginExec(Guid id, DateTime next, int verNum, int ver)
        {
            return this._BasicDAL.Update(a => new AutoTaskModel
            {
                NextExecTime = next,
                LastExecTime = DateTime.Now,
                ExecVerNum = ver,
                IsExec = true
            }, c => c.Id == id && c.ExecVerNum == verNum);
        }

        public void SetTaskTime(Guid id, DateTime execTime)
        {
            if (!this._BasicDAL.Update(new AutoTaskModel
            {
                Id = id,
                NextExecTime = execTime
            }, new string[]
            {
                "NextExecTime"
            }))
            {
                throw new ErrorException("task.set.fail");
            }
        }
    }
}
